package cn.tao.hrm.exception;

import cn.tao.hrm.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //可以在controller执行前，后做一些事情
//@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(BusinessException.class)   //处理异常
    public AjaxResult businessExceptionHandler(BusinessException e){
        //e.printStackTrace();
        ErrorCode errorCode = e.getErrorCode();
        log.error("出错了"+errorCode.getCode()+":"+errorCode.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(errorCode.getCode()).setMessage(errorCode.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)   //处理异常
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getDefaultMessage()+",");
        }
        String msg = sb.toString();
        msg = msg.substring(0,msg.length()-1);
        log.error("出错了"+msg);
        return AjaxResult.me().setSuccess(false).setMessage(msg);
    }



    @ExceptionHandler(Exception.class)   //处理异常
    public AjaxResult exceptionHandler(Exception e){
        //e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode())
                .setMessage(ErrorCode.CODE_500_SYSTEM_ERROR.getMessage());
    }
}
